export class EventList extends Array {
    constructor() {
        super();
        this.eventList = new Map();
        this.stop = false;
    }

    updateEvent(key, event) {
        if (this.eventList.has(key)) {
            this.eventList.set(key, event);
        } else {
            throw new Error('This key not exist!');
        }
    }

    hasEvent(key){
        return this.eventList.has(key);
    }

    addEvent(key, event) {
        if (this.eventList.has(key) && Object.prototype.toString.call(event) === "[object Function]") {
            throw new Error(`${key} is already exist!`);
        }
        this.push(key);
        this.eventList.set(key, event);
    }

    removeEventsByKeys(events) {
        events.forEach(m => {
            this.removeEvent(m);
        });
        events.length = 0;
    }

    removeLastEvent() {
        const index = this.pop();
        if (index) {
            this.eventList.delete(index);
            this.splice(index, 1);
        }
    }

    removeEvent(key) {
        const index = this.indexOf(key);
        if (index >= 0) {
            this.eventList.delete(key);
            this.splice(index, 1);
        }
    }

    removeAll() {
        this.eventList.clear();
        this.length = 0;;
    }

    run(key) {
        if (this.eventList.has(key)) {
            this.eventList.get(key)();
        } else {
            throw new Error('This key not exist!');
        }
    }

    runAll() {
        if(!this.stop)
        for (let i = 0; i < this.length; i++) {
            this.eventList.get(this[i])()
        }
    }
}